import store from '@/store/index.js';

class socketUtil {
	constructor() {
	    this.socketOpen = false;
	}
	
	// 连接socket
	openSocket(url){
		return new Promise((resolve, reject)=>{
			if(!this.socketOpen){
				uni.connectSocket({
					url: url
				})
			}else{
				reject('socket is opened');
			}
		})
	}
	
	// 接收服务器推送
	onSocketMessage(cb){
		uni.onSocketMessage(res=>{
			let val = JSON.parse(res.data);
			cb(val);
		})
	}
	
	// 发送数据
	sendSocketMessage(type, msg){
		return new Promise((resolve, reject)=>{
			if(!this.socketOpen){
				reject('socket is not open');
			}else{
				uni.sendSocketMessage({
					data: `${type}${JSON.stringify(msg)}`,
					success:res=>{
						resolve({
							res: res,
							msg: msg
						});
					}
				})
			}
		})
	}
	
	// 关闭socket
	closeSocket(){
		return new Promise((resolve, reject)=>{
			if(this.socketOpen){
				uni.closeSocket({
					success: res=> {
						resolve('socket close success', res);
					},
					fail: res=>{
						reject('socket close failed', res);
					}
				})
			}else{
				resolve('socket is not opened or socket already closed');
			}
		})
	}
	
	// 监听socket打开
	onSocketOpen(cb){
		uni.onSocketOpen(res=>{
			this.status = 'open';
			this.socketOpen = true;
			cb('socket open success');
		})
	}
	
	// 监听socket关闭
	onSocketClose(cb){
		uni.onSocketClose(res=>{
			this.status = 'close';
			this.socketOpen = false;
			cb('sockect close success');
		})
	}
	
	// 监听socket异常
	onSocketError(cb){
		uni.onSocketError(err=>{
			this.status = 'close';
			this.socketOpen = false;
			cb(err);
		})
	}
}

export default new socketUtil();